<template>
  <div>
    <textarea v-model="formConfig" rows="10" cols="50" placeholder="输入表单配置的JSON"></textarea>
    <button @click="generateForm" class="create">生成表单</button>

    <form @submit.prevent="submitForm">
      <div v-for="(field, index) in formFields" :key="index">
        <label :for="field.name">{{ field.label }}</label>
        <input v-if="field.type === 'text'" :type="field.type" :name="field.name" v-model="formData[field.name]" />
        <select v-else-if="field.type === 'select'" :name="field.name" v-model="formData[field.name]">
          <option v-for="(option, oIndex) in field.options" :key="oIndex" :value="option.value">{{ option.label }}</option>
        </select>
      </div>

      <button type="submit">提交</button>
    </form>

    <div v-if="formOutput">
      <h3>表单数据输出</h3>
      <pre>{{ formOutput }}</pre>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formConfig: '',
      formFields: [],
      formData: {},
      formOutput: ''
    };
  },
  computed: {
    parsedFormConfig() {
      try {
        return JSON.parse(this.formConfig);
      } catch (error) {
        return null;
      }
    }
  },
  methods: {
    generateForm() {
      if (this.parsedFormConfig) {
        this.formFields = this.parsedFormConfig.fields;
        this.formData = {};
        this.formOutput = '';
      } else {
        alert('无效的 JSON 配置');
      }
    },
    submitForm() {
      this.formOutput = JSON.stringify(this.formData, null, 2);
    }
  }
};
</script>

<style>
.create{
  background-color: rgb(113, 210, 240);
  position: absolute;
  margin-top: 60px;
}
</style>